package com.shuo.dsa.niuke;

import com.shuo.dsa.model.ListNode;

/**
 * 输入两个单调递增的链表，输出两个链表合成后的链表，当然我们需要合成后的链表满足单调不减规则
 */
public class MergeTwoList {
    /**
     * 1. 递归法
     */
    public ListNode MergeCur(ListNode list1, ListNode list2) {
        if (list1 == null) return list2;
        if (list2 == null) return list1;
        if (list1.val <= list2.val) {
            list1.next = MergeCur(list1.next, list2);
            return list1;
        } else {
            list2.next = MergeCur(list1, list2.next);
            return list2;
        }
    }

    /**
     * 迭代版
     */
    public ListNode Merge(ListNode list1, ListNode list2) {
        if (list1 == null) return list2;
        if (list2 == null) return list1;
        ListNode sentinel = new ListNode(0);
        ListNode tail = sentinel;
        while (list1 != null && list2 != null) {
            if (list1.val <= list2.val) {
                ListNode next = list1.next;
                tail.next = list1;
                tail = list1;
                tail.next = null;
                list1 = next;
            } else {
                ListNode next = list2.next;
                tail.next = list2;
                tail = list2;
                tail.next = null;
                list2 = next;
            }
        }
        if (list1 != null) tail.next = list1;
        if (list2 != null) tail.next = list2;
        return sentinel.next;

    }
}
